package com.liu.cloud.predicate;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author LIU
 * @version 1.0
 * @description: TODO
 * @date 2023/7/29 17:57
 */
@Slf4j
@Component
public class MyPredicateRoutePredicateFactory extends AbstractRoutePredicateFactory<MyPredicateRoutePredicateFactory.Config> {


    public MyPredicateRoutePredicateFactory() {
        super(Config.class);
    }


    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("param");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String name = serverWebExchange.getRequest().getQueryParams().getFirst("name");
                String param = config.getParam();
                log.info("自定义断言工厂 param: {} , name: {}" , param, name);

                //返回true断言成功
//                return param.equals(name);
                return true;
            }
        };
    }

    @Validated
    public static class Config {
        @NotEmpty
        private String param;

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }
}
